package ocmd

import (
	"osiris/core/consensus"
	"osiris/errors"
	"osiris/logger"
	"osiris/p2p"
	"sync"
)

// PosHandler 作为创世节点启动共识
type PosHandler struct{}

func (handler *PosHandler) Handle(inputs []string, wg *sync.WaitGroup) error {
	defer func() {
		if wg != nil {
			wg.Done()
		}
	}()

	if len(inputs) != 2 {
		return &errors.CommandInputError{
			Msg: "invalid arguments!",
		}
	}

	switch inputs[1] {

	case START:
		logger.Println("pos consensus started.")
		go handler.startPos()

	default:
		return &errors.CommandInputError{
			Msg: "invalid arguments!",
		}
	}

	return nil
}

func (handle *PosHandler) startPos() {
	blockJsonCh := make(chan string)
	//TODO chainID
	//开始记账
	go consensus.OnCreateBlock(0, p2p.GetSelfID(), blockJsonCh)
	//等待blockDto生成
	jsonStr := <-blockJsonCh
	//广播区块
	p2p.OpenStream(p2p.PosProtocol{}, p2p.GetSelfID(), jsonStr, nil)
}

func (hadnler *PosHandler) PrintHelp() {
	logger.Println("usage: pos start")
}
